import { BookList, User, Comment } from '../models';

export default function (router) {
  /**
   * 获取阅读时长
   */
  router.get('/api/front/readtime', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const [user, booklist, commentNum] = await Promise.all([
      User.findById(userid, 'read_time has_exchange'),
      BookList.findOne({ userid }).populate({
        path: 'books.bookid',
        options: {
          select: 'name img_url update_status update_time newest_chapter classify'
        }
      }),
      Comment.countDocuments({ userid })
    ]);
    await ctx.json(true, '获取时长成功', {
      readtime: user.read_time,
      hasExchange: user.has_exchange,
      booklist: booklist?.books || [],
      comment_num: commentNum
    });
  });

  /**
   * 时长兑换书币
   */
  router.post('/api/front/readtime/exchange', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }

    const { userid } = ctx.state.user;
    const thisUser = await User.findById(userid, 'read_time has_exchange');
    const readTime = thisUser.read_time;
    const hasExchange = !!thisUser.has_exchange;
    if (hasExchange) {
      await ctx.json(false, '本周已经兑换过了');
      return;
    }
    const minute = Math.floor(readTime / (1000 * 60));
    // 可兑换个书币数, 3 分钟一个书币
    const num = Math.floor(minute * (10 / 30));
    // 阅读时长校验
    if (readTime === 0) {
      await ctx.json(false, '没有可兑换阅读时长');
      return;
    }
    if ((readTime > 0 && readTime < 60 * 100) || num < 1) {
      await ctx.json(false, '可兑换阅读时长不足');
      return;
    }
    // @ts-ignore
    const awardResult = await User.addAmount(userid, num, '阅读时长兑换奖励');
    if (awardResult) {
      const updateResult = await User.updateOne({ _id: userid }, { $set: { has_exchange: true } });
      if (updateResult.ok === 1 && updateResult.nModified === 1) {
        await ctx.json(true, '兑换书币成功', { num });
      } else {
        // @ts-ignore
        await User.reduceAmount(userid, num);
        await ctx.json(false, '兑换书币失败');
      }
    } else {
      await ctx.json(false, '发放书币失败');
    }
  });
}
